package com.example.goodsmanagementcabinet.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.goodsmanagementcabinet.R;
import com.example.goodsmanagementcabinet.adapter.CheckKeyAdapter;
import com.example.goodsmanagementcabinet.adapter.HandOverAdapter;
import com.example.goodsmanagementcabinet.adapter.KeyAdapter;
import com.example.goodsmanagementcabinet.adapter.KeyUserAdapter;
import com.example.goodsmanagementcabinet.adapter.TakeOverAdapter;
import com.example.goodsmanagementcabinet.base.BaseActivity;
import com.example.goodsmanagementcabinet.base.GoodBoxManagerApp_;
import com.example.goodsmanagementcabinet.bean.KeyBean;
import com.example.goodsmanagementcabinet.bean.OverBean;
import com.example.goodsmanagementcabinet.bean.UserBean;
import com.example.goodsmanagementcabinet.db.DatabaseManager;
import com.example.goodsmanagementcabinet.otto.OttoMsg;
import com.example.goodsmanagementcabinet.serialport.SerialPortConnect;
import com.example.goodsmanagementcabinet.utils.Utils;
import com.squareup.otto.Subscribe;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.Fullscreen;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Fullscreen
@EActivity(R.layout.operating_fragments)
public class HandOverAndTakeOverActivity extends BaseActivity implements View.OnClickListener {

    @ViewById
    GridView keyGridVew;
    @ViewById
    LinearLayout btnhandover, btntakeover;
    @ViewById
    ImageView toHome;
    CheckKeyAdapter keyAdapter;
    CountDownTimer timer;
    boolean isFinish = false;
    Dialog dialog, userInfoDialog;
    Context context;
    private HandOverAdapter hanOverAdapter;
    private TakeOverAdapter takeOverAdapter;
    private ListView mUserGv;
    List<KeyBean> keyBeanList = new ArrayList<>();
    List<KeyBean> openKeys = new ArrayList<>();
    List<UserBean> userList = new ArrayList<>();
    List<UserBean> checkuserList = new ArrayList<>();
    List<OverBean> checOverList = new ArrayList<>();
    List<OverBean> overList = new ArrayList<>();
    @Extra
    public UserBean user;

    @AfterViews
    public void afterViews() {
        context = this;
        btnhandover.setOnClickListener(this);
        btntakeover.setOnClickListener(this);
        toHome.setOnClickListener(this);
        keyAdapter = new CheckKeyAdapter(this);
        keyGridVew.setAdapter(keyAdapter);
        Intent intent = getIntent();
        user = (UserBean) intent.getSerializableExtra("user");
        updateUI();
    }

    @UiThread
    public void updateUI() {
        keyBeanList.clear();
        openKeys.clear();
        userList.clear();
        checkuserList.clear();
        checOverList.clear();
        overList.clear();
        overList = DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).queryOvers(user.getUserId(), "1");
        userList = DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).queryUsers(user.getUserId());
        keyBeanList = DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).queryKeyByUserId(user.getUserId(), "1");
        keyAdapter.notifyRefresh(keyBeanList);
    }

    @Subscribe
    @Background
    public void handlerOtto(OttoMsg msg) {
        if (TextUtils.equals(OttoMsg.OTTO_CHECK_KEY, msg.which)) {
            KeyBean key = (KeyBean) msg.data;
            if (openKeys.size() > 0) {
                boolean stats = true;
                for (KeyBean mykey : openKeys) {
                    if (TextUtils.equals(mykey.getKeyId(), key.getKeyId())) {
                        stats = false;
                    }
                }
                if (stats) {
                    openKeys.add(key);
                }
            } else {
                openKeys.add(key);
            }
        } else if (TextUtils.equals(OttoMsg.OTTO_REMOVE_CHECK_KEY, msg.which)) {
            KeyBean key = (KeyBean) msg.data;
            Iterator<KeyBean> it = openKeys.iterator();
            while (it.hasNext()) {
                KeyBean keys = (KeyBean) it.next();
                if (key.getKeyId().equals(keys.getKeyId())) {
                    it.remove();
                }
            }
        } else if (TextUtils.equals(OttoMsg.OTTO_CHECK_USER, msg.which)) {
            UserBean user = (UserBean) msg.data;
            if (checkuserList.size() > 0) {
                boolean stats = true;
                for (UserBean myuser : checkuserList) {
                    if (TextUtils.equals(myuser.getUserId(), user.getUserId())) {
                        stats = false;
                    }
                }
                if (stats) {
                    checkuserList.add(user);
                }
            } else {
                checkuserList.add(user);
            }
        } else if (TextUtils.equals(OttoMsg.OTTO_REMOVE_USER, msg.which)) {
            UserBean user = (UserBean) msg.data;
            Iterator<UserBean> it = checkuserList.iterator();
            while (it.hasNext()) {
                UserBean users = (UserBean) it.next();
                if (user.getUserId().equals(users.getUserId())) {
                    it.remove();
                }
            }
        } else if (TextUtils.equals(OttoMsg.OTTO_CHECK_OVER, msg.which)) {
            OverBean over = (OverBean) msg.data;
            if (checOverList.size() > 0) {
                boolean stats = true;
                for (OverBean overs : checOverList) {
                    if (TextUtils.equals(over.getOverid(), overs.getOverid())) {
                        stats = false;
                    }
                }
                if (stats) {
                    checOverList.add(over);
                }
            } else {
                checOverList.add(over);
            }
        } else if (TextUtils.equals(OttoMsg.OTTO_REMOVE_OVER, msg.which)) {
            OverBean over = (OverBean) msg.data;
            Iterator<OverBean> it = checOverList.iterator();
            while (it.hasNext()) {
                OverBean overs = (OverBean) it.next();
                if (over.getOverkeyid().equals(overs.getOverid())) {
                    it.remove();
                }
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnhandover:
                if (openKeys.size() <= 0) {
                    speak("请选择要移交的钥匙");
                } else {
                    setEnable(false);
                    UserInfoDialog(userList);
                }
                break;
            case R.id.btntakeover:
                if (overList.size() <= 0) {
                    speak("没有要接收的钥匙");
                } else {
                    OverInfoDialog(overList);
                }
                break;
            case R.id.toHome:
                finish();
                break;
        }
    }

    @UiThread
    public void setEnable(boolean b) {
        keyGridVew.setEnabled(b);
        btnhandover.setEnabled(b);
    }

    private void UserInfoDialog(final List<UserBean> myuserList) {
        if (userInfoDialog == null) {
            userInfoDialog = new Dialog(context, R.style.add_dialog);
            userInfoDialog.setContentView(R.layout.handover_takeover_view);
            userInfoDialog.setCancelable(false);
            WindowManager.LayoutParams layoutParams = userInfoDialog.getWindow().getAttributes();
            userInfoDialog.getWindow().setAttributes(layoutParams);
            Window dialogWindow = userInfoDialog.getWindow();
            dialogWindow.setGravity(Gravity.CENTER);
            hanOverAdapter = new HandOverAdapter(context);
            mUserGv = (ListView) userInfoDialog.findViewById(R.id.addlists);
            mUserGv.setAdapter(hanOverAdapter);
            hanOverAdapter.notifyRefresh(myuserList);
            final LinearLayout mAffirmBtn, mCancelBtn;
            mAffirmBtn = userInfoDialog.findViewById(R.id.mAffirmBtns);
            mCancelBtn = userInfoDialog.findViewById(R.id.mCancelBtn);
            mAffirmBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (checkuserList.size() > 0) {
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
                        String now = format.format(Calendar.getInstance().getTime());
                        List<OverBean> overBeanList = new ArrayList<>();
                        overBeanList.clear();
                        for (KeyBean key : openKeys) {
                            OverBean over = new OverBean();
                            over.setDate(now + "");
                            over.setHandoveruserid(user.getUserId());
                            over.setTakeoveruserid(checkuserList.get(0).getUserId());
                            over.setOverkeyid(key.getKeyId());
                            over.setStatus("1");
                            over.setOverid(now + key.getKeyId());
                            overBeanList.add(over);
                            DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).deleteKeyUserByKeyidAndUserId(user.getUserId(), key.getKeyId());
                        }
                        DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).insertToHandOver(overBeanList);
                        setEnable(true);
                        hidiDialog();
                        updateUI();
                    } else {
                        speak("请选择接收人");
                    }
                }
            });
            mCancelBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    checkuserList.clear();
                    setEnable(true);
                    hidiDialog();
                }
            });

        }
        hanOverAdapter.notifyRefresh(myuserList);
        userInfoDialog.show();
    }


    private void OverInfoDialog(final List<OverBean> myoverList) {
        if (dialog == null) {
            dialog = new Dialog(context, R.style.add_dialog);
            dialog.setContentView(R.layout.handover_takeover_view);
            dialog.setCancelable(false);
            WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
            dialog.getWindow().setAttributes(layoutParams);
            Window dialogWindow = dialog.getWindow();
            dialogWindow.setGravity(Gravity.CENTER);
            takeOverAdapter = new TakeOverAdapter(context);
            mUserGv = (ListView) dialog.findViewById(R.id.addlists);
            mUserGv.setAdapter(takeOverAdapter);
            takeOverAdapter.notifyRefresh(myoverList);
            final LinearLayout mAffirmBtn, mCancelBtn;
            mAffirmBtn = dialog.findViewById(R.id.mAffirmBtns);
            mCancelBtn = dialog.findViewById(R.id.mCancelBtn);
            mAffirmBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (checOverList.size() > 0) {
                        for (OverBean myover : checOverList) {
                            DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).insertToKeyUser(user.getUserId(), myover.getOverkeyid());
                        }
                        DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).updateHandOverState("2", checOverList);
                        hidideleteDialog();
                        updateUI();
                    } else {
                        speak("请选择接收任务");
                    }
                }
            });
            mCancelBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    checkuserList.clear();
                    hidideleteDialog();
                }
            });

        }
        takeOverAdapter.notifyRefresh(myoverList);
        dialog.show();
    }


    @UiThread
    public void hidiDialog() {
        userInfoDialog.dismiss();
    }

    @UiThread
    public void hidideleteDialog() {
        dialog.dismiss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        keyBeanList.clear();
        openKeys.clear();
        userList.clear();
        checkuserList.clear();
        checOverList.clear();
        overList.clear();
        isFinish = true;
        keyAdapter = null;
        hanOverAdapter = null;
        takeOverAdapter = null;
        timer = null;
        dialog = null;
        userInfoDialog = null;
    }
}
